package com.crm.service.system.config;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

public class RedisLock {

    RedissonClient redissonClient;

    public RedisLock(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    /**
     * 互斥锁，seconds秒后自动失效
     * @param key
     * @param seconds
     */
    public boolean lock(String key, int seconds) {
        RLock rLock = redissonClient.getLock(key);
        if (rLock.isLocked()) {
            return false;
        }
        rLock.lock(seconds, TimeUnit.SECONDS);
        return true;
    }

    /**
     * 互斥锁，自动续期
     * @param key
     */
    public boolean lock(String key) {
        RLock rLock = redissonClient.getLock(key);
        // 抢失败就再见
        return rLock.tryLock();
    }

    public boolean blockedLock(String key) {
        // 无脑续期抢
        RLock rLock = redissonClient.getLock(key);
        rLock.lock();
        return true;
    }

    public boolean tryLock(String key, long timeout) throws InterruptedException {
        RLock rLock = redissonClient.getLock(key);
        // 大家一起抢锁，然后抢了指定时间之后，如果不成功，大家别抢了
        return rLock.tryLock(timeout, TimeUnit.MILLISECONDS);
    }





    /**
     * 手动释放锁
     *
     * @param key
     */
    public void unlock(String key) {
        RLock rLock = redissonClient.getLock(key);
        if (rLock.isLocked()) {
            rLock.unlock();
        }
    }

}
